package com.xintonghua.bussiness.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.xintonghua.base.widget.ShowAllListView;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.api.HttpCent;
import com.xintonghua.bussiness.api.manager.AuthManager;
import com.xintonghua.bussiness.base.BaseActivity;
import com.xintonghua.bussiness.bean.Auth;
import com.xintonghua.bussiness.bean.ShopOrderListBean;
import com.xintonghua.bussiness.bean.SubmitLogBean;
import com.xintonghua.bussiness.ui.view.DrawView;
import com.xintonghua.bussiness.util.AbstractBaseAdapter;
import com.xintonghua.bussiness.util.ImageTools;
import com.xintonghua.bussiness.util.JsonUtil;
import com.xintonghua.bussiness.util.MyState;
import com.xintonghua.bussiness.util.MyUtils;
import com.xintonghua.bussiness.util.ViewHolder;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//import static org.feezu.liuli.timeselector.Utils.ScreenUtil.height;

/**
 * Created by liqi on 2018/3/28.
 */

public class SettlementActivity extends BaseActivity implements initTab {


    @BindView(R.id.tabOrder)
    TabLayout tabOrder;
    @BindView(R.id.dv_drawview1huiyuan)
    DrawView dv_drawview1huiyuan;
    @BindView(R.id.dv_drawview2dianzhang)
    DrawView dv_drawview2dianzhang;
    @BindView(R.id.tv_click_qianzi)
    TextView tvClickQianzi;
    @BindView(R.id.showAllListview)
    ShowAllListView showAllListview;
    @BindView(R.id.yingfumoney)
    TextView yingfumoney;
    @BindView(R.id.et_shifumoney)
    EditText etShifumoney;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.btn_refresh_money)
    Button btnRefreshMoney;
    @BindView(R.id.btn_xingxiwuwu)
    Button btnXingxiwuwu;

    List<SubmitLogBean> submitLogBean;
    String money;

    static String homeitem = "homeitem";
    //主页的订单信息传入
    ShopOrderListBean.ListBean homeOrderInfoBean;
    @BindView(R.id.testimg)
    ImageView testimg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement);
        onSimpleActionBar(R.layout.activity_tab_actionbar_simple);
        ButterKnife.bind(this);


        homeOrderInfoBean = (ShopOrderListBean.ListBean) getIntent().getSerializableExtra("homeitem");
        RefreshYuE();
        initTabLayout();
        initUI();


    }

    @Override
    public void initUI() {
        super.initUI();
        submitLogBean = (List<SubmitLogBean>) getIntent().getSerializableExtra("data");
        money = getIntent().getStringExtra("money");
        Log.i("aaa", "submitLogBean====>" + submitLogBean.toString());
        Log.i("aaa", "money====>" + money);
        String mm = money.replaceAll("共计消费:", "");
        String mm1 = money.replaceAll("共计消费：", "");
        yingfumoney.setText("应付:" + mm1);
        initListView();

    }

    int mCurPage = 1;//1会员签字  2店长签字

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == MyState.requestOne && resultCode == Activity.RESULT_OK) {
            Log.i("aaa", "data+=====>" + data);
            if (data != null) {
                Log.i("aaa", "數據===》" + data.getExtras().getSerializable("data"));
                List<Point> pointList = (List<Point>) data.getSerializableExtra("data");
                Log.i("aaa", "目前list大小===》" + pointList.size());
                dv_drawview1huiyuan.setPlist(pointList);
                tvClickQianzi.setVisibility(View.GONE);
            }
        }
        if (requestCode == MyState.requestTwo && resultCode == Activity.RESULT_OK) {
            if (data != null) {

                List<Point> pointList = (List<Point>) data.getSerializableExtra("data");
                dv_drawview2dianzhang.setPlist(pointList);
                tvClickQianzi.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void initTabLayout() {
        dv_drawview1huiyuan.setIsCanDraw(false);
        dv_drawview2dianzhang.setIsCanDraw(false);
        dv_drawview1huiyuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SettlementActivity.this, DialogMemeberSignActivity.class);
                intent.putExtra("title", "会员签字");
                SettlementActivity.this.startActivityForResult(intent, MyState.requestOne);
            }
        });
        dv_drawview2dianzhang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                openActivity(DialogMemeberSignActivity.class);
                Intent intent = new Intent(SettlementActivity.this, DialogMemeberSignActivity.class);
                intent.putExtra("title", "店长签字");
                SettlementActivity.this.startActivityForResult(intent, MyState.requestTwo);
            }
        });
        tabOrder.addTab(tabOrder.newTab().setText("会员签字"));
        tabOrder.addTab(tabOrder.newTab().setText("店长签字"));
        tabOrder.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getText().equals("会员签字")) {
                    mCurPage = 1;
                    dv_drawview1huiyuan.setVisibility(View.VISIBLE);
                    dv_drawview2dianzhang.setVisibility(View.GONE);
                } else if (tab.getText().equals("店长签字")) {
                    mCurPage = 2;
                    dv_drawview1huiyuan.setVisibility(View.GONE);
                    dv_drawview2dianzhang.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void initListView() {
        List<SubmitLogBean.ItemDetailsBean> sub_list = ChangeToAdapterData(submitLogBean);
        showAllListview.setAdapter(new AbstractBaseAdapter<SubmitLogBean.ItemDetailsBean>(sub_list) {
            @Override
            public View getAdapterViewAtPosition(int position, View convertView, ViewGroup parent) {
                SubmitLogBean.ItemDetailsBean bean = getItem(position);
                if (convertView == null) {
                    convertView = LayoutInflater.from(SettlementActivity.this).inflate(R.layout.item_settlement_list_item, null);
                }
                TextView tvType = ViewHolder.get(convertView, R.id.tv_type);
                TextView tvNumber = ViewHolder.get(convertView, R.id.tv_number);
                TextView tvMoney1 = ViewHolder.get(convertView, R.id.tv_money1);

                tvType.setText("" + bean.getProductName());
                tvNumber.setText("" + bean.getAmount());
                tvMoney1.setText("" + bean.getPrice());

                return convertView;
            }
        });
    }

    @Override
    public void dataBack(Object data, int order) {
        super.dataBack(data, order);
        Log.i("aaa", "data===>" + data + "order====>" + order);
        switch (order) {
            case MyState.requestOne:
                try {
                    JSONObject js = new JSONObject(data.toString());
                    tvMoney.setText(js.getString("money"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MyState.requestThree://提交
                MyUtils.mToast(SettlementActivity.this, "提交成功");
                finish();

                break;
            case MyState.requestFour://图片上传
//                data===>[15222915698190.png, 15222915698460.png]order====>4
                try {
                    List<String> list = (List<String>) JsonUtil.getListString(data.toString());
                    Submit(list.get(0), list.get(1));
                    Log.i("aaa", "文件大小" + list.size());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("aaa", "错误");
                }


                break;
        }


    }

    @Override
    public void RefreshYuE() {

//     * @param userId 要查看的用户编号
//     * @param opUserId 操作用户编号
//     * @param serviceOrderId 当前订单号
        Log.i("aaa", "homeOrderInfoBean数据=====>" + homeOrderInfoBean.toString());
        String serviceOrderId = "" + homeOrderInfoBean.getId();
        String userId = "" + homeOrderInfoBean.getConsumptionUserId();
        Auth auth = AuthManager.geteAuth(this);
        String opUserId = "" + auth.getId();

        HttpCent.getInstance(SettlementActivity.this).getUserAmount(userId, opUserId, serviceOrderId, this, MyState.requestOne);
//        HttpCent.getInstance(SettlementActivity.this).getUserAmount("userid", "opuserid", "serviceOrderid", this, MyState.requestOne);

    }

    //来源https://blog.csdn.net/dawanganban/article/details/51148070
    @Override
    public Bitmap ChangeBitmap(List<Point> plist) {
        int width;
        int height;
        if (mCurPage == 1) {
            width = dv_drawview1huiyuan.getWidth();
            height = dv_drawview1huiyuan.getHeight();
        } else {
            width = dv_drawview2dianzhang.getWidth();
            height = dv_drawview2dianzhang.getHeight();
        }
        Log.i("aaa", "canvas-----> width====>" + width + "//height===>" + height);
        //创建一个bitmap
        Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);// 创建一个新的和SRC长度宽度一样的位图
        //将该图片作为画布\
        Canvas canvas = new Canvas(newb);

        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        canvas.drawRect(new Rect(0, 0, width, height), paint);
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);
        paint.setStrokeCap(Paint.Cap.ROUND);
        for (int i = 0; i < plist.size() - 1; i++) {
            if (plist.get(i).x > 0 && plist.get(i).y > 0 && plist.get(i + 1).x > 0 && plist.get(i + 1).y > 0)
                canvas.drawLine(plist.get(i).x, plist.get(i).y, plist.get(i + 1).x, plist.get(i + 1).y, paint);
        }
        // 保存
        canvas.save();
        // 存储
        canvas.restore();
        return newb;
    }

    @Override
    public List<SubmitLogBean.ItemDetailsBean> ChangeToAdapterData(List<SubmitLogBean> sublist) {

        List<SubmitLogBean.ItemDetailsBean> itemlist = new ArrayList<>();
        if (!MyUtils.isNullOrEmpty(sublist)) {
            for (int i = 0; i < sublist.size(); i++) {
                if (!MyUtils.isNullOrEmpty(sublist.get(i).getItemDetails()))
                    for (int j = 0; j < sublist.get(i).getItemDetails().size(); j++) {
                        itemlist.add(sublist.get(i).getItemDetails().get(j));
                    }
            }
        }
        return itemlist;
    }

    @Override//14
    public void Submit(String customerSign, String shopOwnerSign) {
//String serviceOrderId,String operateUserId,String customerSign,String shopOwnerSign,String amountMoney
        String serviceOrderId = "" + homeOrderInfoBean.getId();
        Log.i("aaa", "服务的订单id====》" + serviceOrderId);
        Auth auth = AuthManager.geteAuth();
        String operateUserId = "" + auth.getId();
        String amountMoney = "" + etShifumoney.getText().toString();
        if (TextUtils.isEmpty(amountMoney)) {
            MyUtils.mToast(SettlementActivity.this, "请输入实付金额");
            return;
        }
//             * serviceOrderId	int	y	服务单编号
//                * operateUserId	Int	y	操作用户
//                * customerSign	String	y	客户签字图片
//                * shopOwnerSign	String	y	店长签字图片
//                * amountMoney	dec	y	实付金额
//                *
        HttpCent.getInstance(this).submitServiceOrderBill(serviceOrderId, operateUserId, customerSign, shopOwnerSign, amountMoney, this, MyState.requestThree);
    }

    @Override
    public void saveQianZiImageToSdCard() {
        if (MyUtils.isNullOrEmpty(dv_drawview1huiyuan.getPlist())) {
            MyUtils.mToast(SettlementActivity.this, "请会员签字");
            return;
        }
        if (MyUtils.isNullOrEmpty(dv_drawview2dianzhang.getPlist())) {
            MyUtils.mToast(SettlementActivity.this, "请店长签字");
            return;
        }
        String amountMoney = "" + etShifumoney.getText().toString();
        if (TextUtils.isEmpty(amountMoney)) {
            MyUtils.mToast(SettlementActivity.this, "请输入实付金额");
            return;
        }
        Bitmap bmp1 = ChangeBitmap(dv_drawview1huiyuan.getPlist());
        Bitmap bmp2 = ChangeBitmap(dv_drawview2dianzhang.getPlist());
        String bmp1filename = getApplicationContext().getFilesDir().getAbsolutePath() + "/bmp1" + System.currentTimeMillis();
        String bmp2filename = getApplicationContext().getFilesDir().getAbsolutePath() + "/bmp2" + System.currentTimeMillis();
        ImageTools.savePhotoToSDCard(bmp1, bmp1filename);
        ImageTools.savePhotoToSDCard(bmp2, bmp2filename);
        File file1 = new File(bmp1filename);
        File file2 = new File(bmp2filename);
        if (!file1.exists()) {
            MyUtils.mToast(SettlementActivity.this, "文件保存失败，请检查是否有权限");
            return;
        }
        if (!file2.exists()) {
            MyUtils.mToast(SettlementActivity.this, "文件保存失败，请检查是否有权限");
            return;
        }
        List<String> list = new ArrayList<>();
        list.add(file1.getAbsolutePath());
        list.add(file2.getAbsolutePath());
        ImageTools.loadImages(SettlementActivity.this, list, this, MyState.requestFour);
    }

    @OnClick({R.id.btn_refresh_money, R.id.btn_xingxiwuwu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_refresh_money://刷新余额
                RefreshYuE();
                break;
            case R.id.btn_xingxiwuwu://信息无误按钮
                saveQianZiImageToSdCard();
                break;
        }
    }
}

interface initTab {
    //tab
    void initTabLayout();

    void initListView();

    void RefreshYuE();//刷新余额

    //将canvas画的点转为bitmap
    Bitmap ChangeBitmap(List<Point> list);//

    //转化成适配器数据（主要将数据合并）
    List<SubmitLogBean.ItemDetailsBean> ChangeToAdapterData(List<SubmitLogBean> submitLogBeanslist);

    //信息无误，确认上传
    void Submit(String customerSign, String shopOwnerSign);//

    //上传步骤1：保存签字图片到sdcard
    void saveQianZiImageToSdCard();


}
